# -*- coding: utf-8 -*-
# FileName:     custom_module.py
# time:         23/2/1 001 下午 2:03
# Author:       Zhou Hang
# Description:  I don't want to write

from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QPainter, QColor, QMouseEvent, QTextCursor
from PyQt5.QtWidgets import QWidget, QMenu, QTextEdit


class RoundWidget(QWidget):
    """圆角边框类，带有鼠标拖动功能"""
    def __init__(self, parent=None):
        super(RoundWidget, self).__init__(parent)
        self._tracking = False
        self._startPos = None
        self._endPos = None
        self.padding = 5  # 设置边距
        self.round_width = 20
        # 设置 窗口无边框和背景透明 *必须
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)

    def paintEvent(self, event):
        # 圆角
        pat = QPainter(self)
        pat.setRenderHint(pat.Antialiasing)  # 抗锯齿
        pat.setBrush(QColor(255, 255, 204))  # 仅仅适合qt_material中的dark_pink.xml系列主题
        pat.setPen(Qt.transparent)

        rect = self.rect()
        # 设置矩形距离边框的距离
        rect.setLeft(self.padding)
        rect.setTop(self.padding)
        rect.setWidth(rect.width() - self.padding)
        rect.setHeight(rect.height() - self.padding)
        pat.drawRoundedRect(rect, self.round_width, self.round_width)

    # 无边框情况下也能移动窗口
    def mouseMoveEvent(self, e: QMouseEvent):  # 重写移动事件
        if self._tracking:
            self._endPos = e.pos() - self._startPos
            self.move(self.pos() + self._endPos)

    def mousePressEvent(self, e: QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._startPos = QPoint(e.x(), e.y())
            self._tracking = True

    def mouseReleaseEvent(self, e: QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._tracking = False
            self._startPos = None
            self._endPos = None

    def contextMenuEvent(self, event):
        """右击触发菜单，有一个退出功能"""
        menu = QMenu(self)
        quitAction = menu.addAction("退出")
        action = menu.exec_(self.mapToGlobal(event.pos()))
        if action == quitAction:
            self.close()


class ZTextEdit(QTextEdit):
    def __init__(self, parent):
        super(ZTextEdit, self).__init__(parent)
        self.origin_text = ''

    def focusInEvent(self, QFocusEvent):
        self.setText(self.origin_text)

    def focusOutEvent(self, QFocusEvent):
        self.origin_text = self.toPlainText()
        try:
            self.setMarkdown(self.origin_text)
        except Exception as e:
            print(repr(e))
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.End)  # 还可以有别的位置
        self.setTextCursor(cursor)


def main():
    pass


if __name__ == "__main__":
    main()

